from django import forms
from django.core.exceptions import ValidationError


class BaseForm(forms.Form):
    @property
    def errors(self):
        """Return a str for the error raised from the form."""
        if self._errors is None:
            self.full_clean()
        return self._errors.as_text()


class NullBooleanSelect(forms.NullBooleanSelect):
    def value_from_datadict(self, data, files, name):
        value = data.get(name)
        if value in [True, 'True', 'true', '1', 1]:
            return True

        if value in [False, "False", 'false', '0', 0]:
            return False

        return None


class NullBooleanField(forms.NullBooleanField):
    widget = NullBooleanSelect

    def to_python(self, value):
        return value

    def validate(self, value):
        if value is None and self.required:
            raise ValidationError(self.error_messages['required'], code='required')
